<template>
  <basic-container>
    
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               ref="crud"
               v-model="form"
               :defaults.sync="showColumn"
               :permission="permissionList"
               :page.sync="page"
               :before-open="beforeOpen"
                            
               @on-load="onLoad">
      <template slot-scope="scope" slot="menu">
        <el-button type="text"
                   size="small"
                   icon="el-icon-s-operation"
                   @click.stop="openUsersDialog(scope.row)">所有在线用户
        </el-button>
      </template>
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-refresh"
                   v-if="permission.tenant_edit"
                   @click.stop="openPushBaseDialog">推送基础数据
        </el-button>
      </template>
    </avue-crud>
    
    <!-- 
      设置租户权限
     -->
    <el-dialog title="在线用户" width='50%' :close-on-click-modal='false' :visible.sync="getOnlineDialog" @close="closeUserDialog">
      <div class="commandClass">
        <div>
          <el-input size="small" style="width:200px;margin:0 16px;" v-model="userName" placeholder="请输入名字"></el-input>
          <el-button  size="small"  type="primary" @click="queryUserName">查 询</el-button>
        </div>
        <avue-crud :option="userOption"
                :data="userList"
                ref="crud"
                v-model="userForm"
                >
            <template slot-scope="scope" slot="menu">
                  <el-button type="primary"
                            size="small"
                            icon="el-icon-clear"
                            @click.stop="clearStorage(scope.row)">清空缓存
                  </el-button>
            </template>
        </avue-crud>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeUserDialog">关 闭</el-button>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
import {exportSysTenantInfoExcel,generateLicense,saveOrUpdateSysTenantInfo,saveOrUpdateSysTenantInfoList,saveSysTenantInfo,saveSysTenantInfoList,deleteSysTenantInfo,querySysTenantInfo,querySysTenantInfoListPage,updateSysTenantInfo,deleteSysTenantInfoList} from '@/api/system/sysTenantInfoApi';
import {mapGetters} from 'vuex';
import { reqCommonMsg } from '@/util/reqCommonMsg';
import {filterFormat} from '@/util/util';
import {getToken} from '@/util/auth'
import {Base64} from 'js-base64';
import NProgress from 'nprogress'
export default {
  data() {
    return {
      //socket
      socket: null,
      noticeSocket: '',
      userName: '',
      userList: [],

      //打开在线用户
      getOnlineDialog: false,
      userForm:{},
      userOption: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 130,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:false,          
        menuWidth: 200,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:false,
        refreshBtn: false,
        columnBtn: false,
        column: [
          {
            label: '用户ID',
            prop: 'userName', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '用户姓名',
            prop: 'realName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
        ]
      },
      userData:[],

      form: {},
      selectionList: [],
      loading: true, 
      showColumn: [],
      option: {
        labelPosition: 'right',
        labelSuffix: '：',
        labelWidth: 130,
        dialogTop: '50',
        indexFixed:true, 
        stripe:true,
        calcHeight: 80,
        searchMenuSpan: 6,
        tip: false,
        border: true,
        index: true,
        selection: false,
        addBtn: false,
        viewBtn: false,
        delBtn: false,
        editBtn: false,
        cancelBtn: true,
        printBtn:false,
        saveBtn: true,
        filterBtn:false,          
        menuWidth: 270,
        dialogMenuPosition: 'center',
        dialogDirection:'rtl',
        dialogType:'dialog',
        dialogFullscreen:false,
        dialogClickModal:false,
        dialogWidth: '70%',
        highlightCurrentRow:  true,
        searchShow:false,
        refreshBtn: false,
        column: [
          {
            label: '租户ID',
            prop: 'userTenantId', 
            type: 'select', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '租户名称',
            prop: 'tenantName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '联系人名',
            prop: 'contactName', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [{
              required:  true,
              message: '请输入内容',
              trigger: 'blur'
            }],
            dicData:[]
          },
          {
            label: '联系电话',
            prop: 'contactPhoneNo', 
            type: 'input', 
            search: false,
            searchMmultiple: false,
            searchLabelWidth: 100,
            multiple: false,
            span: 12,
            sortable: false,
            hide: false,
            overHidden: true,
            rules: [
              {
                required:  true,
                message: '请输入内容',
                trigger: 'blur'
              },
              {
                // 检查手机号
                validator: (rule, value, callback) => {
                  if(value != '' && !this.$validate.isMobile(value)){
                    callback(new Error('请输入11位手机号码！'));
                  }
                  else{
                    callback();
                  }
                }
              }
            ],
            dicData:[]
          }
        ]
      },
      data: [],
      // 请求参数区
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      reqParams: {
        singleBody: {},
        listBody: [{}],
        sqlCondition:[],
        orderRule: {},
        currentPage: 1,
        pageSize: 10
      },
      commonData: null,
      conditions: [],
      orderRules: [],
      singleBody: {}
    };
  },
  computed: {
    ...mapGetters(['website','userInfo','permission']),
    permissionList() {
      return {
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push({id : ele.id});
      });
      return ids;
    } 
  },
  methods: {
    /**
     * 筛选用户
     */
    queryUserName(){
      this.userList = this.userData.filter(item => item.realName.indexOf(this.userName) >= 0);
    },
    /**
     * 打开用户对话框
     */
    openUsersDialog(row){
      this.getOnlineDialog = true;
      this.getAllOnlineUser(row);  
    },
    /** 
     * 消息通知
     */
    getAllOnlineUser(row) {
      const that = this;
      if (typeof (WebSocket) == 'undefined') {
        this.$notify({
          title: '提示',
          message: '当前浏览器无法接收实时报警信息，请使用谷歌浏览器！',
          type: 'warning',
          duration: 0
        });
      } else {
        // 实例化socket，这里我把用户名传给了后台，使后台能判断要把消息发给哪个用户，其实也可以后台直接获取用户IP来判断并推送
        const socketUrl = 'ws://socket.dooleen.com:8012/webSocket/sendMsg/'+row.tenantId+'/PC/userControlCommand/system'+this.userInfo.userName+'/'+this.userInfo.realName+'/'+ Base64.encode(this.userInfo.avatar  || 'abc');
        if(this.socket == null){
          this.socket = new WebSocket(socketUrl);
        }
        
        // 监听socket打开
        this.socket.onopen = function() {
          that.$console.log('=>>getAllOnlineUser 浏览器WebSocket已打开');
        };
        // 监听socket消息接收
        this.socket.onmessage = function(msg) {
          that.$console.log('getAllOnlineUser msg==',msg);
          let msgData = JSON.parse(msg.data);
          that.userData = msgData.userList;
          that.userList = msgData.userList;
        };
        // 监听socket错误
        this.socket.onerror = function() {
          that.$console.error('==>>getAllOnlineUser 接收通知，服务器错误，无法接收实时信息');
        };
        // 监听socket关闭
        this.socket.onclose = function() {
          that.socket = null;
          that.$console.log('getAllOnlineUser WebSocket已关闭');
        }
      }
    },
    /**
     * 关闭对话框
     */
    closeUserDialog(){
      if(this.socket){
        this.socket.close();
      }
      this.getOnlineDialog = false;
    },
    /**
     * 清空缓存指令
     */
    clearStorage(row){
      if(this.socket){
        let userName = row.userName.split('#');
        this.socket.send('{"command":"clearStorage", "userName":"'+userName[2]+'","message": "menus"}');
      }
      else{
        this.$notify({
          title: '提示',
          message: '主机连接失败，请刷新重试！',
          type: 'warning',
          duration: 0
        });
      }
    },
    /**
     * 加载列表数据
     */
    onLoad(page) {
      this.loading = true;
      this.reqParams =  {
        singleBody: this.singleBody,
        listBody: [{}],
        sqlCondition: this.conditions,
        orderRule: this.orderRules,
        currentPage: page.currentPage, 
        pageSize: page.pageSize
      }
      this.commonData = reqCommonMsg(this.reqParams)
      querySysTenantInfoListPage(this.commonData).then(res => {
        const data = res.data.body;
        this.page.total = data.total;
        this.data = data.listBody;
        this.loading = false;
      }, error => {
        this.loading = false; 
      });
    },
   
    /**
     * 生成秘钥
     */
    generateLicense(){
      if (this.selectionList.length !== 1) {
        this.$message.warning('请选择一个租户数据');
        return;
      }
      else if (this.selectionList[0].tenantId == this.website.defaultTenantId) {
        this.$message.warning('超级租户不需要创建秘钥！');
        return;
      }
      else if(this.selectionList[0].licenseContent == ''){
        this.$message.warning('租户秘钥参数内容不能为空');
        return;
      }
      this.reqParams.singleBody =  JSON.parse(this.selectionList[0].licenseContent);
      this.commonData = reqCommonMsg(this.reqParams)
      generateLicense(this.commonData).then(() => {
        this.singleBody={};
        this.$message({
          customClass:'zZindex',
          type: 'success',
          message: '秘钥创建成功!'
        });
      }, error => {
        //this.$console.log(error);
      });
    },
  },
  created() {

  }
};
</script>
<style>
  .commandClass .el-table__header{
   display: none !important;
 }
 .commandClass .avue-crud__menu{
   display: none !important;
   min-height: 1px !important;
 }
</style>
